package org.example.interceptor;

import org.example.po.ShoppingUser;
import org.example.rvo.ResultVO;
import org.example.util.JSONUtil;
import org.example.util.JWTUtil;
import org.example.util.TUserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 针对除了登录注册等不需要用户信息的操作来实现绑定token
 * @author jianma
 */
public class OtherInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        System.out.println("-------------------------");
        //从前端传入的header的token key中判断是否有值
        String token = request.getHeader("token");
        if(token != null){

            //token过期和没过期的判断
            boolean b = JWTUtil.checkToken(token);
            if(b){
                Claims claims = JWTUtil.parseJWT(token);
                Map<String,Object> claim = (Map)claims.get("user");
                ShoppingUser shoppingUser = new ShoppingUser();
                shoppingUser.setId((String) claim.get("id"));
                shoppingUser.setUserName((String)claim.get("userName"));
                shoppingUser.setUserGender((String)claim.get("userGender"));
                shoppingUser.setUserHeadImg((String)claim.get("userHeadImg"));
                shoppingUser.setUserPhone((String)claim.get("userPhone"));
                //request.setAttribute("shoppingUser",shoppingUser);
                TUserThreadLocal.set(shoppingUser);
              return true;
            }else{
                PrintWriter out = response.getWriter();
                out.write(JSONUtil.obj2str(ResultVO.failure("200011","token失效")));
                out.flush();
                return false;
            }
        }else{
            PrintWriter out = response.getWriter();
            out.write(JSONUtil.obj2str(ResultVO.failure("200011","token失效")));
            out.flush();
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TUserThreadLocal.remove();
    }
}
